//
//  PersonalViewController.m
//  LuCaiZhu
//
//  Created by stella Ma on 2018/11/14.
//
#import "UIColor+NN.h"
#import "CardTextCell.h"
#import "CKPuslichTool.h"
#import "CardPicCell.h"
#import "TKAlertCenter.h"
#import "ValidateTools.h"
#import "UserModel.h"
#import "HandleNetProduct.h"
#import "NetworkConfig.h"
#import <objc/runtime.h>
#import <AipOcrSdk/AipOcrSdk.h>
#import "PersonalViewController.h"

@interface PersonalViewController (){
    NSString *cardNo;
    NSString *userName;
    NSString *cardPlace;
    NSString *startTime;//开始日期
    NSString *endTime;//失效日期
    NSString *birthday;//生日
    
}
@property (weak, nonatomic) IBOutlet UIView *timeView;
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
@property (weak, nonatomic) IBOutlet UIButton *submitBt;
@property (weak, nonatomic) IBOutlet UITableView *mTableView;
@property (strong, nonatomic)NSArray *datas;
@property (strong, nonatomic)UIImage *cardBeforeImg;
@property (strong, nonatomic)UIImage *cardBackImg;



@end

@implementation PersonalViewController{
    // 默认的识别成功的回调
    void (^_successHandler)(id);
    // 默认的识别失败的回调
    void (^_failHandler)(NSError *);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"实名认证";
    _datePicker.backgroundColor = [UIColor whiteColor];
//    _datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
//    [_datePicker setTimeZone:[NSTimeZone defaultTimeZone]];
//    cardNo = @"610324198808042842";
//    cardPlace = @"陕西省扶风县";
//    userName = @"马青";
    cardNo = @"";
    cardPlace = @"";
    userName = @"";
    startTime = @"";
    endTime = @"";
    birthday = @"";
    _cardBeforeImg = [UIImage imageNamed:@"img1"];
    _cardBackImg = [UIImage imageNamed:@"img2"];
    [[AipOcrService shardService] authWithAK:@"YbiZ64wTwOW1uVIs1eNzg0YM" andSK:@"CztL9EMZl6nbkgkHAt0QXzG1WR28KjDO"];
     [self configCallback];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f4f4f4"];
    UIViewSetRadius(_submitBt, 22, 0, nil);
    _datas = @[@"客户姓名：",@"证件号码：",@"签发机关：",@"签发日期：",@"失效日期："];
}
//身份证正面
- (void)localIdcardOCROnlineFront {
    
    UIViewController * vc =
    [AipCaptureCardVC ViewControllerWithCardType:CardTypeLocalIdCardFont
                                 andImageHandler:^(UIImage *image) {
                                     
                                     [[AipOcrService shardService] detectIdCardFrontFromImage:image
                                                                                  withOptions:nil
                                                                               successHandler:^(id result){
                                                                                   _successHandler(result);
                                                                                   // 这里可以存入相册
                                                                                   _cardBeforeImg = image;
                                                                                   
                                                                                   dispatch_async(dispatch_get_main_queue(), ^{
                                                                                       //回调或者说是通知主线程刷新，
                                                                                       [[TKAlertCenter defaultCenter]postAlertWithMessage:@"扫描正面成功"];
                                                                                   });
                                                                                   //UIImageWriteToSavedPhotosAlbum(image, nil, nil, (__bridge void *)self);
                                                                               }
                                                                                  failHandler:_failHandler];
                                 }];
    [self presentViewController:vc animated:YES completion:nil];
    
    
}


//身份证背面
- (void)localIdcardOCROnlineBack{
    
    UIViewController * vc =
    [AipCaptureCardVC ViewControllerWithCardType:CardTypeLocalIdCardBack
                                 andImageHandler:^(UIImage *image) {
                                     
                                     [[AipOcrService shardService] detectIdCardBackFromImage:image
                                                                                 withOptions:nil
                                                                              successHandler:^(id result){
                                                                                  _successHandler(result);
                                                                                  // 这里可以存入相册
                                                                 
                                                                                  dispatch_async(dispatch_get_main_queue(), ^{
                                                                                      //回调或者说是通知主线程刷新，
                                                                                     [[TKAlertCenter defaultCenter]postAlertWithMessage:@"扫描背面成功"];
                                                                                  });
                                                                                  _cardBackImg = image;                               // UIImageWriteToSavedPhotosAlbum(image, nil, nil, (__bridge void *)self);
                                                                              }
                                                                                 failHandler:_failHandler];
                                 }];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)configCallback {
    __weak typeof(self) weakSelf = self;
    
    // 这是默认的识别成功的回调
    _successHandler = ^(id result){
        NSLog(@"%@", result);
        
        if(result[@"words_result"]){
            if([result[@"words_result"] isKindOfClass:[NSDictionary class]]){
                [result[@"words_result"] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                    if([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]){
                        if ([key isEqualToString:@"姓名"]) {
                            userName = obj[@"words"];
                        }
                        if ([key isEqualToString:@"公民身份号码"]) {
                            cardNo = obj[@"words"];
                        }
                        
                        if ([key isEqualToString:@"签发机关"]) {
                            cardPlace = obj[@"words"];
                            
                        }
//
                        
                        if ([key isEqualToString:@"出生"]) {
                            NSDate *dateTime =  [CKPuslichTool dateFromCustomString:obj[@"words"] format:@"yyyyMMdd"];
                            birthday = [CKPuslichTool stringFromCustomFormatDate:dateTime format:@"yyyy.MM.dd"];
                        }
                        if ([key isEqualToString:@"失效日期"]) {
                            if ([obj[@"words"] isEqualToString:@"长期"]) {
                                endTime = @"长期";
                            }else{
                                NSDate *dateTime =  [CKPuslichTool dateFromCustomString:obj[@"words"] format:@"yyyyMMdd"];
                                endTime = [CKPuslichTool stringFromCustomFormatDate:dateTime format:@"yyyy.MM.dd"];
                            }
                            
                        }
                        //
                        if ([key isEqualToString:@"签发日期"]) {
                            NSDate *dateTime =  [CKPuslichTool dateFromCustomString:obj[@"words"] format:@"yyyyMMdd"];
                            startTime = [CKPuslichTool stringFromCustomFormatDate:dateTime format:@"yyyy.MM.dd"];
                        }
                    }
                    
                }];
            }
            
        }
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf.mTableView reloadData];
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }];
    };
    
    _failHandler = ^(NSError *error){
        NSLog(@"%@", error);
        NSString *msg = [NSString stringWithFormat:@"%li:%@", (long)[error code], [error localizedDescription]];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[[UIAlertView alloc] initWithTitle:@"识别失败" message:msg delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
        }];
    };
}


- (IBAction)timeChoose:(UIButton *)sender {
    
    self.timeView.hidden = YES;
        
    if (sender.tag == 0) {
        return;
    }
    
    NSDate *theDate = _datePicker.date;//该属性返回选中的时间
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//返回一个日期格式对象
    dateFormatter.dateFormat = @"YYYY.MM.dd";
    if (self.timeView.tag == 3) {
        
        startTime = [dateFormatter stringFromDate:theDate];
        NSIndexPath *indexp = [NSIndexPath indexPathForRow:3 inSection:1];
        [self.mTableView reloadRowsAtIndexPaths:@[indexp] withRowAnimation:UITableViewRowAnimationFade];
    }else if (self.timeView.tag == 4) {
        endTime = [dateFormatter stringFromDate:theDate];
        NSIndexPath *indexp = [NSIndexPath indexPathForRow:4 inSection:1];
        [self.mTableView reloadRowsAtIndexPaths:@[indexp] withRowAnimation:UITableViewRowAnimationFade];
    }
//    [self.mTableView reloadData];
}


#pragma mark ===================得到当前时间=============
- (NSDate *)getCurrentTime{
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init]; [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateTime=[formatter stringFromDate:[NSDate date]];
    NSDate *date = [formatter dateFromString:dateTime];
    return date;
    
}
//日期对比
- (int)compareOneDay:(NSDate *)currentDay withAnotherDay:(NSDate *)BaseDay {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *currentDayStr = [dateFormatter stringFromDate:currentDay];
    NSString *BaseDayStr = [dateFormatter stringFromDate:BaseDay];
    NSDate *dateA = [dateFormatter dateFromString:currentDayStr];
    NSDate *dateB = [dateFormatter dateFromString:BaseDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", currentDay, BaseDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1 is in the future");
        return 1;
        
    } else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
        
    } //NSLog(@"Both dates are the same");
    return 0;
    
} //使用







- (IBAction)submit:(id)sender {
    if (userName.length==0) {
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"请扫描或输入客户姓名"];
        return;
    }
    if (cardNo.length==0) {
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"请扫描或输入证件号码"];
        return;
    }
    if (![ValidateTools validateIDNo:cardNo]) {
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"证件号码错误"];
        return;
    }
    if (cardPlace.length==0) {
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"请扫描或输入签发机关"];
        return;
    }
    if (endTime.length==0) {
        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"请扫描或输入失效日期"];
        return;
    }
    
    if (![endTime isEqualToString:@"长期"]) {
        NSDate *currentDay = [self getCurrentTime];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy.MM.dd"];
        NSDate *FinalDay = [dateFormatter dateFromString:endTime];
        int isOn = [self compareOneDay:currentDay withAnotherDay:FinalDay];
        if (isOn == 1) {
            NSLog(@"在日期之后");
            [[TKAlertCenter defaultCenter]postAlertWithMessage:@"您的身份证件已失效"];
            return;
        }else if (isOn == 0) {
            NSLog(@"在日期当天");
            
        }else if (isOn == -1) {
            NSLog(@"在日期之前");
            
        }
    }
    
   
    
    UserModel *user = [UserModel getUser];
    
    NSDictionary *params=@{@"AAAMethodName":@"IDConfirm",
                           @"AccountPhone":user.Phone,
                           @"IDConfirmName":userName,
                           @"IDConfirmNumber":cardNo,
                           @"signingorganization":cardPlace,
                           @"IDValidity":[NSString stringWithFormat:@"%@-%@",startTime,endTime],
                           @"status":@"完成"};
    [HandleNetProduct realNameConfirmForParams:params Success:^(NSDictionary *data) {
        if (self.returnBlock) {
            self.returnBlock();
        }
        [self.navigationController popViewControllerAnimated:YES];
    } Failure:^(NSString *errorInfo) {
        
    }];
    
}

- (void)checkingCardPic:(UIButton *)sender {
    if (sender.tag == 0) {
        [self localIdcardOCROnlineFront];
    }else{
        [self localIdcardOCROnlineBack];
    }
}

- (void)textFieldDidEnd:(UITextField *)textField{
    if (textField.text.length ==0) {
        return;
    }
    switch (textField.tag) {
        case 0:
        {
            userName = textField.text;
        }
            break;
        case 1:
        {
            cardNo = textField.text;
        }
            break;
        case 2:
        {
            cardPlace = textField.text;
        }
            break;
      
            
        default:
            break;
    }
}

#pragma mark - Table view data source
//
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return _datas.count;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CardPicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CardPicCell"];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
        cell.mPic1.image = _cardBeforeImg;
        cell.mPic2.image = _cardBackImg;
   
        [cell.bigBt1 addTarget:self action:@selector(checkingCardPic:) forControlEvents:UIControlEventTouchDown];
        [cell.bigBt2 addTarget:self action:@selector(checkingCardPic:) forControlEvents:UIControlEventTouchDown];
        return cell ;
    }
    CardTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CardTextCell"];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    cell.leftLabel.text = _datas[indexPath.row];
    cell.mTextField.enabled = YES;
    cell.mTextField.tag = indexPath.row;
    [cell.mTextField addTarget:self action:@selector(textFieldDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
    
    if (indexPath.row == 0) {
        cell.mTextField.text = userName?:@"";
        cell.mTextField.placeholder = @"请扫描或输入客户姓名";
    }else if (indexPath.row == 1){
        cell.mTextField.text = cardNo?:@"";
        cell.mTextField.placeholder = @"请扫描或输入证件号码";
    }else if (indexPath.row == 2){
        cell.mTextField.text = cardPlace?:@"";
        cell.mTextField.placeholder = @"请扫描或输入签发机关";
    }else if (indexPath.row == 3){
        cell.mTextField.enabled = NO;
        cell.mTextField.text = startTime?:@"";
        cell.mTextField.placeholder = @"请扫描或选择签发日期";
    }else{
        cell.mTextField.text = endTime?:@"";
        cell.mTextField.enabled = NO;
        cell.mTextField.placeholder = @"请扫描或选择失效日期";
    }
    return cell ;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.timeView.tag = indexPath.row;
    if (indexPath.row == 3) {
        NSLog(@"333333333");
        self.timeView.hidden = NO;
    }else if (indexPath.row ==4){
        NSLog(@"444444444");
        self.timeView.hidden = NO;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 380;
    }
 
    return 45;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01f;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (!self.timeView.hidden) {
        self.timeView.hidden = YES;
    }
}

@end
